package com.zy.community.mini.service.index;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zy.community.common.core.domain.r.ZyResult;
import com.zy.community.community.domain.ZyOwner;
import com.zy.community.community.domain.ZyOwnerRoom;
import com.zy.community.community.domain.ZyOwnerRoomRecord;
import com.zy.community.community.domain.vo.AuditType;
import com.zy.community.community.domain.vo.RoomStatus;
import com.zy.community.community.mapper.ZyOwnerMapper;
import com.zy.community.community.mapper.ZyOwnerRoomMapper;
import com.zy.community.community.mapper.ZyOwnerRoomRecordMapper;
import com.zy.community.framework.security.mini.MiniContextUtils;
import com.zy.community.mini.factory.BindFactory;
import com.zy.community.web.controller.mini.index.dto.FamilyDto;
import com.zy.community.web.controller.mini.index.dto.MemberDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 家庭成员服务
 */
@Service
public class MiniFamilyService {
    @Resource
    private ZyOwnerMapper zyOwnerMapper;
    @Resource
    private ZyOwnerRoomMapper zyOwnerRoomMapper;
    @Resource
    private BindFactory bindFactory;
    @Resource
    private ZyOwnerRoomRecordMapper zyOwnerRoomRecordMapper;

    /**
     * 查看当前用户绑定房屋对应的亲属信息
     *
     * @param communityId 社区Id
     * @return 家庭成员信息
     */
    @Transactional(readOnly = true)
    public ZyResult<List<FamilyDto>> findFamilyInfo(Long communityId) {
        if (communityId == null) return ZyResult.fail(400, "社区Id不能为空");
        String openId = MiniContextUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) return ZyResult.fail(401, "用户未认证");
        ZyOwner zyOwner = zyOwnerMapper.selectOne(new QueryWrapper<ZyOwner>().eq("owner_open_id", openId));
        if (zyOwner == null) return ZyResult.fail(404, "该用户不存在");

        List<Long> bindRoomIds = zyOwnerRoomMapper.findBindRoomIds(communityId, zyOwner.getOwnerId());
        if (CollectionUtils.isEmpty(bindRoomIds)) {
            return ZyResult.fail(404, "没有家庭成员信息");
        }
        List<FamilyDto> familyDtos = new ArrayList<>();
        bindRoomIds.forEach(roomId -> {
            FamilyDto dto = new FamilyDto();
            dto.setRoomId(roomId);
            FamilyDto basicFamily = zyOwnerRoomMapper.findBasicFamily(roomId, zyOwner.getOwnerId());
            dto.setBuildingName(basicFamily.getBuildingName());
            dto.setRoomName(basicFamily.getRoomName());
            dto.setUnitName(basicFamily.getUnitName());
            List<MemberDto> members = zyOwnerRoomMapper.findMembers(roomId);
            //查询当前用户是否是该房间的业主
            ZyOwnerRoom zyOwnerRoom = zyOwnerRoomMapper.selectOne(new QueryWrapper<ZyOwnerRoom>()
                    .eq("owner_id", zyOwner.getOwnerId())
                    .eq("owner_type", "yz")
                    .eq("room_id", roomId)
                    .eq("room_status", "Binding")
            );
            if (zyOwnerRoom != null) {
                //当前用户是该房间的业主
                members.forEach(memberDto -> {
                    memberDto.setCanUnBind(true);
                });
            } else {
                //只能解绑自己
                members.stream().filter(member -> member.getOwnerId().equals(zyOwner.getOwnerId()))
                        .findFirst().get().setCanUnBind(true);
            }
            dto.setMembers(members);
            familyDtos.add(dto);
        });
        return ZyResult.data(familyDtos);

    }


    /**
     * 解绑
     *
     * @param roomId  房屋信息
     * @param ownerId 用户信息
     * @return 解绑结果
     */
    @Transactional
    public ZyResult<String> unBindOption(Long roomId, Long ownerId) {
        if (roomId == null || ownerId == null) {
            return ZyResult.fail(400, "信息不完整");
        }
        String openId = MiniContextUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) return ZyResult.fail(401, "用户未认证");
        ZyOwner zyOwner = zyOwnerMapper.selectOne(new QueryWrapper<ZyOwner>()
                .eq("owner_open_id", openId)
        );
        if (zyOwner == null) return ZyResult.fail(404, "该用户不存在");
        ZyOwnerRoom zyOwnerRoom = zyOwnerRoomMapper.selectOne(new QueryWrapper<ZyOwnerRoom>()
                .eq("room_id", roomId)
                .eq("owner_id", ownerId)
        );
        if (zyOwnerRoom == null) return ZyResult.fail(404, "记录不存在");
        zyOwnerRoomMapper.delete(new QueryWrapper<ZyOwnerRoom>()
                .eq("room_id", roomId)
                .eq("owner_id", ownerId)
        );
        ZyOwnerRoomRecord bindRecord = bindFactory.createBindRecord(zyOwnerRoom);
        bindRecord.setRoomStatus(RoomStatus.Unbind);
        bindRecord.setCreateById(zyOwner.getOwnerId());
        bindRecord.setRecordAuditType(AuditType.App);
        bindRecord.setRecordAuditOpinion("由[" + zyOwner.getOwnerRealName() + "]解绑");
        zyOwnerRoomRecordMapper.insert(bindRecord);
        return ZyResult.success("解绑成功");
    }


}
